package hander

import (
	"encoding/json"
	"strconv"
	"tech-sys-mgr/cache"
	"tech-sys-mgr/moder"
	"tech-sys-mgr/pkg"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}

	redis_login := "redis_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"mas":  "错误3次",
			"code": 500,
		})
		return
	}

	var user moder.User
	err := moder.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "查询失败",
			"code": 500,
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"mas":  "用户名为空",
			"code": 500,
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"mas":  "密码错误3次",
				"code": 500,
			})
			return
		}
		c.JSON(200, gin.H{
			"mas":  "错误",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "正确",
		"code": 200,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var user []moder.User
	redis_list := "redis_list" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list).Result()
	if result == "" {
		moder.DB.Offset(offset).Limit(size).Order("id asc").Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_list, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	var total int64
	moder.DB.Model(&moder.User{}).Count(&total)
	c.JSON(200, gin.H{
		"mas":   "成功",
		"code":  500,
		"tata":  user,
		"total": total,
	})
	return
}
